﻿using Set_File_Rw;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.Ports;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using TestFireBroadcastingHostPhone.RelatedInstruments;
using TestFireBroadcastingHostPhone.Source;
using static TestFireBroadcastingHostPhone.RelatedInstruments.DS1102;

namespace TestFireBroadcastingHostPhone.ViewModel
{
    public class InstrumentsConfigMV : ViewModelBase
    {
        /// <summary>
        /// 连接数字示波器的标志
        /// </summary>
        public bool PYOscilloscopeConnect = false;
        /// <summary>
        /// 开启示波器自动检测的标志
        /// </summary>
        private bool PYOscilloscopeTest = false;
        public InstrumentsConfigMV() 
        {
            Text_ResultSetting = new ObservableCollection<string>();
        }
        /// <summary>
        /// 测试示波器定时器
        /// </summary>
        private DispatcherTimer? TestOscilloscopeTimer;
        public ICommand InstrumentsConfig_LoadedCommand => new RelayCommand(OnInstrumentsConfig_Loaded);
        /// <summary>
        /// 仪器设置窗体载入
        /// </summary>
        /// <param name="obj"></param>
        public void OnInstrumentsConfig_Loaded(object obj)
        {
            Text_ACPowerAddress = "1";
            Text_OscilloscopeIP_Address = "192.168.200.201";
            Text_Btn_OpenACPowerContent = "开启";
            Background_Btn_OpenACPower = new SolidColorBrush(Colors.Gray);
            Btn_ConnectOscilloscopeContent = "连接";
            Btn_TestOscilloscopeData_Content = "测试";
        }
        public string _ACPowerAddress = string.Empty;
        /// <summary>
        /// 程控交流源地址
        /// </summary>
        public string Text_ACPowerAddress
        {
            get => this._ACPowerAddress;
            set
            {
                this._ACPowerAddress = value;
                OnPropertyChanged();
            }
        }

        public string _OscilloscopeIP_Address = string.Empty;
        /// <summary>
        /// 示波器IP地址
        /// </summary>
        public string Text_OscilloscopeIP_Address
        {
            get => this._OscilloscopeIP_Address;
            set
            {
                this._OscilloscopeIP_Address = value;
                OnPropertyChanged();
            }
        }

        public string _ACPowerVoltageInput = string.Empty;
        /// <summary>
        /// 程控交流源电压设置
        /// </summary>
        public string Text_ACPowerVoltageInput
        {
            get => this._ACPowerVoltageInput;
            set
            {
                this._ACPowerVoltageInput = value;
                OnPropertyChanged();
            }
        }

        public string _Btn_OpenACPowerContent = string.Empty;
        /// <summary>
        /// 打开程控交流源按键内容
        /// </summary>
        public string Text_Btn_OpenACPowerContent
        {
            get => this._Btn_OpenACPowerContent;
            set
            {
                this._Btn_OpenACPowerContent = value;
                OnPropertyChanged();
            }
        }

        public Brush _Btn_OpenACPowerBackground = new SolidColorBrush(Colors.Gray);
        /// <summary>
        /// 打开程控交流源按键背景颜色
        /// </summary>
        public Brush Background_Btn_OpenACPower
        {
            get => this._Btn_OpenACPowerBackground;
            set
            {
                this._Btn_OpenACPowerBackground = value;
                OnPropertyChanged();
            }
        }

        public string _Btn_ConnectOscilloscope = string.Empty;
        /// <summary>
        /// 示波器按键内容
        /// </summary>
        public string Btn_ConnectOscilloscopeContent
        {
            get => this._Btn_ConnectOscilloscope;
            set
            {
                this._Btn_ConnectOscilloscope = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<string> _ResultSetting = new ObservableCollection<string> { };
        /// <summary>
        /// 输出文本结果
        /// </summary>
        public ObservableCollection<string> Text_ResultSetting
        {
            get { return _ResultSetting; }
            set
            {
                _ResultSetting = value;
                OnPropertyChanged();
            }
        }

        public string _Btn_TestOscilloscopeData_Content;
        /// <summary>
        /// 示波器检测按钮内容
        /// </summary>
        public string Btn_TestOscilloscopeData_Content
        {
            get => this._Btn_TestOscilloscopeData_Content;
            set
            {
                this._Btn_TestOscilloscopeData_Content = value;
                OnPropertyChanged();
            }
        }

        public string _Text_OscilloscopeTestTime;
        /// <summary>
        /// 检测时间
        /// </summary>
        public string Text_OscilloscopeTestTime
        {
            get => this._Text_OscilloscopeTestTime;
            set
            {
                this._Text_OscilloscopeTestTime = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 绑定程控交流源事件
        /// </summary>
        public ICommand Btn_SetACPower_Command => new RelayCommand(OnBtn_SetACPower);
        /// <summary>
        /// 程控交流源设置
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_SetACPower(object obj)
        {
            string err_info = string.Empty;
            string default_file_path = Directory.GetCurrentDirectory() + "\\RecordData\\RelatedRecord.ini";
            if (StaticInfo.instrumentsControl.ACPowerPort == null)
            {
                StaticInfo.instrumentsControl.ACPowerPort = new SerialPort();
                if (!string.IsNullOrEmpty(SystemConfigMV.systemconfigMV.Cmb_AN97002SerialPort_SelectValue))
                {
                    if (SystemConfigMV.systemconfigMV.AreSerialPortsUnique())
                    {
                        StaticInfo.instrumentsControl.ACPowerPort.PortName = SystemConfigMV.systemconfigMV.Cmb_AN97002SerialPort_SelectValue;
                        Set_Data_Rw.Write(SystemConfigMV.configpath, default_file_path, "交流源串口", StaticInfo.instrumentsControl.ACPowerPort.PortName, out err_info);
                    }
                    else
                    {
                        MessageBox.Show("选择串口存在冲突，请检查串口参数配置!");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("请配置程控交流源串口!");
                    return;
                }
            }
            byte address = Convert.ToByte(Text_ACPowerAddress);//获取程控交流源地址
            if (!string.IsNullOrEmpty(Text_ACPowerVoltageInput))
            {
                switch (SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue)
                {
                    case "新程控交流源":
                        StaticInfo.instrumentsControl.ACPowerPort.BaudRate = NAN97002S.NAN97002S_BaudRate;//新程控交流源波特率
                        StaticInfo.instrumentsControl.nAN97002S.Function_SetVoltageAndFrequencyOnline(StaticInfo.instrumentsControl.ACPowerPort, address, Convert.ToDecimal(Text_ACPowerVoltageInput), 500, 10, out err_info);//50Hz，锁定
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            AppendTextToTextBox(err_info);//打印错误信息
                        }
                        else
                        {
                            AppendTextToTextBox("程控交流源电压设置成功，当前交流源电压为：" + Text_ACPowerVoltageInput);//设置成功
                        }
                        break;
                    case "旧程控交流源":
                        StaticInfo.instrumentsControl.ACPowerPort.BaudRate = AN97002H.AN97002H_BaudRate;//旧程控交流源波特率
                        err_info = StaticInfo.instrumentsControl.An97002H.ACPower_vSetParameters(address, Convert.ToDecimal(Text_ACPowerVoltageInput), 50, true, StaticInfo.instrumentsControl.ACPowerPort);//500Hz，锁定
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            AppendTextToTextBox(err_info);//打印错误信息
                        }
                        else
                        {
                            AppendTextToTextBox("程控交流源电压设置成功，当前交流源电压为：" + Text_ACPowerVoltageInput);//设置成功
                        }
                        break;
                    default:
                        AppendTextToTextBox("未选择交流源类型!");
                        break;
                }
            }
        }
        /// <summary>
        /// 绑定打开程控交流源事件
        /// </summary>
        public ICommand Btn_OpenOrClose_ACPower_Command => new RelayCommand(OnBtn_OpenOrClose_ACPower);
        /// <summary>
        /// 打开程控交流源
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_OpenOrClose_ACPower(object obj)
        {
            string err_info = string.Empty;
            byte address = Convert.ToByte(Text_ACPowerAddress);
            if (StaticInfo.instrumentsControl.ACPowerPort is null)
            {
                MessageBox.Show("程控交流源串口未打开!");
                return;
            }
            if (!string.IsNullOrEmpty(Text_ACPowerVoltageInput))
            {
                if (!StaticInfo.instrumentsControl.open_power)
                {
                    StaticInfo.instrumentsControl.OpenACPower(SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue,SystemConfigMV.systemconfigMV.Cmb_AN97002SerialPort_SelectValue!,out err_info);//开启程控交流源
                    if (string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("程控交流源已开启");//打开成功
                        Text_Btn_OpenACPowerContent = "关闭";
                        Background_Btn_OpenACPower = new SolidColorBrush(Colors.Red);
                    }
                    else
                    {
                        AppendTextToTextBox(err_info);//打印错误信息
                    }
                }
                else
                {
                    StaticInfo.instrumentsControl.CloseACPower(SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue,SystemConfigMV.systemconfigMV.Cmb_AN97002SerialPort_SelectValue!,out err_info);//关闭程控交流源
                    if (string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("程控交流源已关闭");//关闭成功
                        Text_Btn_OpenACPowerContent = "开启";
                        Background_Btn_OpenACPower = new SolidColorBrush(Colors.Gray);
                    }
                    else
                    {
                        AppendTextToTextBox(err_info);//打印错误信息
                    }
                }
            }
            else
            {
                MessageBox.Show("参数未设置!");
            }
        }
        /// <summary>
        /// 绑定连接示波器事件
        /// </summary>
        public ICommand Btn_ConnectOscilloscope_Command => new RelayCommand(OnBtn_ConnectOscilloscope);
        /// <summary>
        /// 连接示波器
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_ConnectOscilloscope(object obj)
        {
            string err_info = string.Empty;
            if (!PYOscilloscopeConnect)
            {
                StaticInfo.instrumentsControl.dS1102.DS_Connect(Text_OscilloscopeIP_Address, out err_info);
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("示波器连接错误" + "错误信息：" + err_info);
                }
                else
                {
                    AppendTextToTextBox("示波器连接成功");
                    PYOscilloscopeConnect = true;
                    Btn_ConnectOscilloscopeContent = "断开";
                }
            }
            else
            {
                StaticInfo.instrumentsControl.dS1102.DS_DisConnect();
                PYOscilloscopeConnect = false;
                Btn_ConnectOscilloscopeContent = "连接";
                AppendTextToTextBox("示波器已断开连接");
            }
        }

        public ICommand Btn_QureyOscilloscopeData_Command => new RelayCommand(OnBtn_QureyOscilloscopeData);
        /// <summary>
        /// 查询数字示波器有效值
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_QureyOscilloscopeData(object obj)
        {
            string err_info = string.Empty;
            decimal getvalue = decimal.Zero;

            if (PYOscilloscopeConnect)
            {
                getvalue = StaticInfo.instrumentsControl.dS1102.DS_Query_Value(Text_OscilloscopeIP_Address, DS_Channel_Enum.CHAN1, DS_Query_Item_Enum.VRMS, out err_info);
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("示波器查询错误" + "错误信息：" + err_info);
                }
                else
                {
                    AppendTextToTextBox(getvalue.ToString());
                }
            }
            else
            {
                MessageBox.Show("请连接数字示波器!");
            }
        }
        /// <summary>
        /// 检测示波器事件
        /// </summary>
        public ICommand Btn_TestOscilloscopeData_Command => new RelayCommand(OnBtn_TestOscilloscopeData);
        /// <summary>
        /// 测试示波器
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_TestOscilloscopeData(object obj)
        {
            if (TestOscilloscopeTimer == null)
            {
                TestOscilloscopeTimer = new DispatcherTimer();
            }
            if (PYOscilloscopeConnect)
            {
                if (!string.IsNullOrEmpty(Text_OscilloscopeTestTime))
                {
                    int time = Convert.ToInt32(Text_OscilloscopeTestTime);
                    if (time > 50)
                    {
                        if (!PYOscilloscopeTest)
                        {
                            if (Text_ResultSetting.Count > 0) Text_ResultSetting.Clear();
                            TestOscilloscopeTimer.Tick += TestOscilloscope_TimerTick;
                            TestOscilloscopeTimer.Interval = TimeSpan.FromMilliseconds(time);
                            TestOscilloscopeTimer.Start(); //发送对时
                            Btn_TestOscilloscopeData_Content = "停止";
                            PYOscilloscopeTest = true;
                        }
                        else
                        {
                            TestOscilloscopeTimer.Stop();
                            Btn_TestOscilloscopeData_Content = "测试";
                            PYOscilloscopeTest = false;
                        }
                    }
                    else
                    {
                        MessageBox.Show("测试时间不能低于50ms!");
                    }
                }
                else
                {
                    MessageBox.Show("请输入测试时间!");
                }
            }
            else
            {
                MessageBox.Show("请连接数字示波器!");
            }
        }
        /// <summary>
        /// 示波器检测定时器
        /// </summary>
        private void TestOscilloscope_TimerTick(object? sender, EventArgs e)
        {
            string err_info = string.Empty;
            decimal getvalue = decimal.Zero;
            getvalue = StaticInfo.instrumentsControl.dS1102.DS_Query_Value(Text_OscilloscopeIP_Address, DS_Channel_Enum.CHAN1, DS_Query_Item_Enum.VRMS, out err_info);
            if (!string.IsNullOrEmpty(err_info))
            {
                AppendTextToTextBox("示波器查询错误" + "错误信息：" + err_info);
            }
            else
            {
                AppendTextToTextBox(getvalue.ToString());
            }
        }
        /// <summary>
        /// 文本框新增一行的方法
        /// </summary>
        /// <param name="textToAdd">新增文本框的内容</param>
        public void AppendTextToTextBox(string textToAdd)
        {
            DateTime now = DateTime.Now;
            string timeFormat = $"{now:HH:mm:ss}";
            string formattedTime = $"{timeFormat} ";
            string finalText = formattedTime + textToAdd;
            Text_ResultSetting.Add(finalText);
            Application.Current.Dispatcher.BeginInvoke(() => 
            {
                InstrumentsConfig.instruments.Lst_ResultSetting.SelectedItem = InstrumentsConfig.instruments.Lst_ResultSetting.Items[InstrumentsConfig.instruments.Lst_ResultSetting.Items.Count - 1];
                InstrumentsConfig.instruments.Lst_ResultSetting.ScrollIntoView(InstrumentsConfig.instruments.Lst_ResultSetting.SelectedItem); 
            });
        }
    }
}
